package com.privatetime.web.interceptor;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.privatetime.model.User;
import com.privatetime.service.UserService;
import com.privatetime.web.ActionStateConstants;

public class AuthenticationInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	private UserService userService;

	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		ActionContext actionContext = ai.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) actionContext
				.get(StrutsStatics.HTTP_REQUEST);
		Map<String, User> session = (Map<String, User>) ActionContext
				.getContext().get(ActionContext.SESSION);
		if (session != null
				&& session.get(ActionStateConstants.SESSION_USER) != null) {
			return ai.invoke();
		}

		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("privatetime")) {
					String value = cookie.getValue();
					if (StringUtils.isNotBlank(value)) {
						String[] splitValue = value.split("==");
						String userName = splitValue[0];
						String passWord = splitValue[1];
						User loginUser = userService.userLogin(userName,
								passWord);
						if (loginUser != null) {
							session.put(ActionStateConstants.SESSION_USER,
									loginUser);
						} else {// user not found
							return ActionStateConstants.LOGIN;
						}
					} else {// no cookie
						return ActionStateConstants.LOGIN;
					}
					return ai.invoke();
				}
			}
		}
		return ActionStateConstants.LOGIN;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
